package com.yzdbx.task;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.RandomUtil;
import com.yzdbx.utils.GenUtil;

import java.math.BigDecimal;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;

import static com.yzdbx.utils.DbUtil.getMaxId;
import static com.yzdbx.utils.GenUtil.CUR_DATE;

/**
 * @BelongsProject: SERVEVICE-DATA-GEN
 * @BelongsPackage: com.yzdbx.task
 * @Author: lk
 * @CreateTime: 2025-05-14
 * @Description: TODO
 * @Version: 1.0
 */
@SuppressWarnings("all")
public class SalefOrderRunnable implements Exe {


    private Connection connection;

    private static final String ALL_CLIENT_SQL = "select id from  jcClientInformation";
    private static final String ALL_PRODUCT_SQL = "select id from gy02ProductRepository where productClassification = '产成品' ";
    private static final String ALL_USER_SQL = "select memberId as ID from corp_member where memberId != 'admin123'";
    public static final ThreadLocal<List<Integer>> GEN_ORDER_IDS = new ThreadLocal<>();

    public SalefOrderRunnable(Connection connection) {
        this.connection = connection;
    }

    public boolean execute(int count) {
        List<Integer> genOrderIds = new ArrayList<>();
        try {
            //查询客户信息
            PreparedStatement statement = connection.prepareStatement(ALL_CLIENT_SQL);
            ResultSet resultSet = statement.executeQuery();
            List<Integer> clientIds = new ArrayList<>();

            while (resultSet.next())
                clientIds.add(resultSet.getInt("ID"));

            //查询产品库
            List<Integer> productIds = new ArrayList<>();
            statement = connection.prepareStatement(ALL_PRODUCT_SQL);
            resultSet = statement.executeQuery();
            while (resultSet.next())
                productIds.add(resultSet.getInt("ID"));

            //查询用户
            List<String> userIds = new ArrayList<>();
            statement = connection.prepareStatement(ALL_USER_SQL);
            resultSet = statement.executeQuery();
            while (resultSet.next())
                userIds.add(resultSet.getString("ID"));


            int maxOrderId = getMaxId(connection, "salesOrders");


            for (int i = 1; i <= count; i++) {

                int orderCount = 0;

                int curOrderId = ++maxOrderId;
                genOrderIds.add(curOrderId);
                //生成若干条订单明细
                int detailCount = RandomUtil.randomInt(1, 4);

                int detailMaxId = getMaxId(connection, "xs02SalesOrderBreakdown");
                for (int j = 1; j <= detailCount; j++) {
                    List<Integer> proIds = new ArrayList<>();
                    statement = connection.prepareStatement("insert into xs02SalesOrderBreakdown (id,productInformation,number,associatedSalesOrders,unitPrice,quantityOfShipments,numberOfRemainingShipments,amount) values (" +
                            "?,?,?,?,?,?,?,?" +
                            ")");

                    statement.setInt(1, detailMaxId + j);
                    statement.setInt(2, GenUtil.getNoRepeatId(RandomUtil.randomEle(productIds), proIds, productIds));
                    int number = 65 * RandomUtil.randomInt(1, 11);
                    statement.setInt(3, number);
                    statement.setInt(4, curOrderId);
                    BigDecimal unitPrice = RandomUtil.randomBigDecimal(BigDecimal.ONE, BigDecimal.valueOf(20)).setScale(2, BigDecimal.ROUND_HALF_UP);
                    statement.setBigDecimal(5, unitPrice);
                    statement.setInt(6, number);
                    statement.setInt(7, 0);
                    statement.setBigDecimal(8, unitPrice.multiply(BigDecimal.valueOf(number)).setScale(2, BigDecimal.ROUND_HALF_UP));
                    orderCount += number;
                    statement.execute();

             }
                statement = connection.prepareStatement("insert into salesOrders (id,f4ed,clientInformation,dateOfOrder,applicant,numberOfOrders,created,modified,approvalStatus,modifyer,synchronisingFolderFailedSS) values (" +
                        "?,?,?,?,?,?,?,?,?,?,?)");

                statement.setInt(1, curOrderId);
                statement.setString(2, GenUtil.getNoFromTable(connection, "XS", "salesOrders", "f4ed"));
                statement.setInt(3, RandomUtil.randomEle(clientIds));
                statement.setDate(4, Date.valueOf(CUR_DATE.get()));
                String userId = RandomUtil.randomEle(userIds);
                statement.setString(5, userId);
                statement.setInt(6, orderCount);
                statement.setTimestamp(7, GenUtil.CUR_TIME_STAMP.get());
                statement.setTimestamp(8, GenUtil.CUR_TIME_STAMP.get());
                statement.setString(9, "已通过");
                statement.setString(10, userId);
                statement.setString(11, userId);

                statement.execute();
            }

        } catch (Exception e) {

           throw new RuntimeException("数据生成失败",e);
        }

        GEN_ORDER_IDS.set(genOrderIds);

        return Boolean.TRUE;
    }


}
